﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using StudentManagement.ViewModels;
using StudentManagement.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using StudentManagement.Services;

namespace StudentManagement.Controllers
{
    public class AccountController : Controller
    {
        private readonly IUserService userService;

        public AccountController(IUserService userService)
        {
            this.userService = userService;
        }

        [HttpGet]
        public IActionResult Login(LoginViewModel model, string additonal)
        {
            var principal = HttpContext.User;
            if (principal != null) {
                model.UserName = principal.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Name)?.Value;
                model.Password = principal.Claims.FirstOrDefault(x => x.Type == "password")?.Value;
                
                string remeber;
                Request.Cookies.TryGetValue("remember", out remeber);
                model.RememberMe = Convert.ToBoolean(remeber);
            };

            return View(model);
        }
         

    [HttpPost]
        public async Task<IActionResult> Login(LoginViewModel model)
        {
            IEnumerable<ModelError> allErrors = null;

            if (!ModelState.IsValid) {
                // get first error and display
                allErrors = ModelState.Values.SelectMany(v => v.Errors);
                if (allErrors.Count() > 0) {
                    ViewBag.ErrorInfo = allErrors.Last().ErrorMessage;
                }
                return View(model);
            }

            if (userService.FindUser(model.UserName, model.Password) == null) {
                ViewBag.ErrorInfo = "用户名或者密码不正确!";
                return View(model);
            }

            // 创建cookie保存用户信息，将序列化用户信息并储存在cookie中
            List<Claim> claims = new List<Claim>() {
                new Claim(ClaimTypes.Name, model.UserName), 
                new Claim("password", model.Password),    
            };

            var userPrincipal = new ClaimsPrincipal(
                new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme));


            AuthenticationProperties authProperties = null;           
            authProperties = new AuthenticationProperties {
                ExpiresUtc = DateTime.UtcNow.AddDays(1),
                IsPersistent = model.RememberMe,
                AllowRefresh = false
            };          

            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, userPrincipal, authProperties);
            
            CookieOptions options = new CookieOptions();            
            options.Expires = DateTime.Now.AddDays(1);
            HttpContext.Response.Cookies.Append("remember", model.RememberMe.ToString(), options);
            HttpContext.Session.SetString("CurrentUser", model.UserName);
            return RedirectToAction("Index", "Student");
        }

        [HttpPost]
        public async Task<IActionResult> Logout()
        {
            await HttpContext.SignOutAsync();
            Response.Cookies.Delete("remember");
            return RedirectToAction("Login", "Account");
        }
    }
}
